<template>
  <div>
    <el-breadcrumb separator="/" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/admin/menu/list">角色管理</a></el-breadcrumb-item>
    </el-breadcrumb><br><br>


    角色名称：
    <el-input placeholder="请输入角色名称" v-model="input.name" clearable @input="listRoleByCondition()"
              style="width: 200px;margin: 0"></el-input>
    &nbsp;&nbsp;
    更新时间：
    <el-date-picker
        v-model="updateTimeQuery"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="listRoleByCondition()">
    </el-date-picker>

<!--    <el-button type="primary" icon="el-icon-search" @click="listRoleByCondition()">搜索</el-button>-->

    &nbsp;&nbsp;
    <el-dropdown>
      <el-button type="primary" style="margin-left: 10px">{{ roleStatus }}</el-button>
      <el-dropdown-menu slot="dropdown">
        <a href="javascript:void(0)" @click="queryStatus(1)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>正常使用</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(2)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>禁用状态</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(3)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>全部状态</el-dropdown-item>
        </a>
      </el-dropdown-menu>
    </el-dropdown>

    &nbsp;&nbsp;
    <el-button type="primary" @click="cardPopup(0)" style="margin: 0 0 15px 0">新增</el-button>

    &nbsp;&nbsp;
    <el-button type="danger"  @click="handleDeleteList()">批量删除</el-button>
    <br><br>


    <template>
      <el-table
          :data="tableData"
          ref="multipleTable"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="40">
        </el-table-column>
        <el-table-column fixed prop="id" label="ID" width="60"></el-table-column>
        <el-table-column fixed prop="name" label="角色名称" width="120"></el-table-column>
        <el-table-column fixed prop="description" label="角色描述" width="400"></el-table-column>
        <el-table-column fixed prop="gmtCreate" label="注册时间" width="160"></el-table-column>
        <el-table-column fixed prop="gmtModified" label="修改时间" width="160"></el-table-column>
        <el-table-column fixed prop="status" label="角色状态" width="80">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.status==1?'角色已启用':'角色已禁用'" placement="top">
              <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inacti
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleEdit(scope.row)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="180"
            >
          <template slot-scope="scope" >

              <el-button type="primary" icon="el-icon-s-grid" circle
                         @click="drawer = true;
                          menuPopups();menuByRoleId(scope.row.id)
                        "></el-button>
              <el-button type="primary" icon="el-icon-edit" circle
                         @click="cardPopup(scope.row.id);
                       selectById(scope.row.id)"></el-button>
              <el-button type="danger" icon="el-icon-delete" circle
                         @click="handleDelete(scope.row)"></el-button>

          </template>
        </el-table-column>
      </el-table>
    </template>


    <template>
      <el-dialog
          append-to-body
          :title= dialogVisibleTitle
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="40%"
          @close="closeDialog('ruleForm')">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">

          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" maxlength="25" show-word-limit clearable
                      style="width: 300px;"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="description">
            <el-input
                type="textarea"
                placeholder="这里可以畅所欲言哦~"
                v-model="ruleForm.description"
                maxlength="30"
                style="width:300px"
                show-word-limit>
            </el-input>
          </el-form-item>

          <el-form-item label="是否启用" prop="status">
            <el-tooltip :content="ruleForm.status=='1'?'启用':'禁用'" placement="top">
              <el-switch
                  v-model="ruleForm.status"
                  active-color="#13ce66"
                  inactive-color="#E4E7ED"
                  :active-value="1"
                  :inactive-value="0"
              ></el-switch>
            </el-tooltip>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="closeDialog('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </template>


    <!--权限菜单-->
    <template>
      <el-drawer
          title="权限菜单"
          append-to-body
          :before-close="handleClose"
          :visible.sync="drawer"
          direction="rtl"
          custom-class="demo-drawer"
          ref="drawer"
      >
        <div class="demo-drawer__content">
          <el-form ref="ruleForm" label-width="180px" class="demo-ruleForm">
            <el-tree
                :data="treeData"
                ref="tree"
                show-checkbox
                node-key="key"
                :default-expanded-keys = [0]
                :default-checked-keys = romeMenuEchoArray
                style="bottom: -10px"
                :props="defaultProps"
            />
          </el-form>
          <div class="demo-drawer__footer" style="position: relative;top: 30px;">
            <el-button @click="cancelForm">取 消</el-button>
                <el-button
                    type="primary"
                    @click="handleCloses"
                    >提 交
                </el-button>
          </div>
        </div>
      </el-drawer>
    </template>


    <!--页码-->
    <template>
      <div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 7, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countDate">
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {

      ruleForm: {
        id: '',
        name: '',
        description: '',
        sort: '',
        status: '1'
      },   // 添加 / 修改数据集
      rules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        description: [
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
      },            // 输入验证
      input: {
        name: '',
        description: '',
        status: '1',
        updateTimeStart: '',
        updateTimeEnd: '',
        pageNum: '0',
        pageSize: '5'
      },    // 查询条件集
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },    // 日期查询条件
      updateTimeQuery: [],     // 日期查询结果

      treeData: [],            // 权限树数据源
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      romeMenuEchoArray:[],    // 角色权限回填数组

      tableData: [],           // 条件查询结果集
      multipleSelection: [],   // 批量删除复选框

      roleStatus: '正常使用',   // 按钮：角色状态筛选的名称
      AddOrSetByRoleId: 0,    // 区别方法【添加 ro 修改】
      dialogVisible: false,   // 弹出框状态(添加 or 修改功能)，默认隐藏
      dialogVisibleTitle: '添加用户',   // 弹框标题---【添加 or 修改功能】
      drawer: false,          // 弹出框状态(权限树列表)，默认隐藏
      props: {multiple: true},// 默认弹窗的默认设置

      currentPage: 1,         // 当前页码
      currentSize: 5,         // 每页展示信息数量
      countDate: 0,           // 条件查询结果集数量
    }
  },
  methods: {

    /**
     * 弹窗：添加 OR 修改
     */
    cardPopup(roleId) {
      if (roleId === 0) {
        this.ruleForm.status = 1;       // 默认角色状态为启用
        this.AddOrSetByRoleId = 0;      // 调用添加方法
        this.dialogVisibleTitle = "添加角色";   // 设置弹窗标题
      } else {
        this.dialogVisibleTitle = "修改角色";
        this.AddOrSetByRoleId = roleId;  // 调用修改方法
      }
      this.dialogVisible = true;        // 打开弹窗
    },


    /**
     * 业务：添加 OR 修改
     */
    submitForm() {
      let addOrSetData = this.ruleForm;
      if (addOrSetData.name === null || addOrSetData.name === undefined || addOrSetData.name === ''){
        this.$message({type: 'error', message: "角色名称不能为空"})
        return;
      }

      if (this.AddOrSetByRoleId === 0) {
        console.log("即将发送【新增角色】请求：参数{"+
            "name="+addOrSetData.name+"，"+
            "sort="+addOrSetData.sort+"，"+
            "status="+addOrSetData.status+"，"+
            "description="+addOrSetData.description+
            +"}")
        /**
         * 添加角色
         */
        let path = "http://localhost:9090/system/role/creatRole"
        this.axios.post(path, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "创建角色成功"
              });
              this.listRoleByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      } else {
        console.log("即将发送【修改角色】请求：参数{"+
            "id="+addOrSetData.id+"，"+
            "name="+addOrSetData.name+"，"+
            "sort="+addOrSetData.sort+"，"+
            "status="+addOrSetData.status+"，"+
            "description="+addOrSetData.description+
            +"}")
        let path = "http://localhost:9090/system/role/updateById"
        if (addOrSetData.password === "******") {
          addOrSetData.password = ""
        }
        /**
         * 修改角色
         */
        this.axios.post(path, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '修改用户成功!'
              });
              this.listRoleByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }
      this.closeDialog();
      this.dialogVisible = false;   // 关闭弹窗
    },


    /**
     * 业务：赋予角色权限
     * 按钮：提交按钮---权限列表弹窗
     */
    handleCloses(done) {
      let path = "http://localhost:9090/system/role/updateMenuByRoleId/"+this.ruleForm.id
      let data = this.$refs.tree.getCheckedKeys()
      console.log("【为角色ID为【"+this.ruleForm.id+"】赋予权限的id：【"+data+"】")
      this.axios.post(path, data).then((response) => {
        switch (response.data.code) {
          case 200:
            this.dialogVisible = false;
            this.$message({
              type: 'success',
              message: '修改角色权限成功!'
            });
            break;
          default:
            this.$message({
              type: 'error',
              message: response.data.message
            })
            break;
        }
      })
      this.drawer = false;
      this.closeDialog();
    },


    /**
     * 业务：修改角色状态
     * @param id
     */
    handleEdit(row) {
      this.$confirm('此操作将使名为【'+row.name+'】的角色无法使用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let path = "http://localhost:9090/system/role/updateById"
        console.log("用户ID：" + row.id + ",账号状态" + row.status)
        let data = {
          id: row.id,
          status: row.status
        }
        this.axios.post(path, data).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '修改成功',
              });
              this.listRoleByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              });
              if (row.status === 0) {
                row.status = 1;
              } else {
                row.status = 0;
              }
              break;
          }
        })
      }).catch(() => {
        if (row.status === 0) {
          row.status = 1;
        } else {
          row.status = 0;
        }
      })
    },


    /**
     * 业务：删除
     * @param id
     */
    handleDelete(row) {
      this.$confirm('此操作将永久删除i【'+row.name+'】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("即将向数据库发送删除【"+row.name+"】请求，角色ID=【" + row.id + "】")
        // let array = {id: row.id, url: '解决请求体为空'}
        this.axios.post("http://localhost:9090/system/role/deleteById", row).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listRoleByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              });
              break;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    /**
     * 业务：批量删除
     */
    handleDeleteList() {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'info',
          message: '请勾选需要删除的品牌'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }
      this.$confirm('此操作将永久删除ID为【'+array+'】的角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/system/role/deleteByIds", array).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listRoleByCondition()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },


    /**
     * 业务：获取批量删除业务选中的复选框
     * @param val
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },


    /**
     * 条件查询，返回结果集
     */
    listRoleByCondition() {

      // 获取时间搜索的条件
      if (this.updateTimeQuery != null) {
        this.input.updateTimeStart = this.updateTimeQuery[0];
        this.input.updateTimeEnd = this.updateTimeQuery[1];
      } else {
        this.input.updateTimeStart = null;
        this.input.updateTimeEnd = null;
      }

      /**
       * 查询满足查询条件的信息数量
       */
      this.axios.post("http://localhost:9090/system/role/getCountAll", this.input).then((response) => {
        this.countDate = response.data;
        let temp = response.data;

        if (response.data>0) {
          let tempPageNum = temp % this.currentSize ===0? temp/ this.currentSize : temp / this.currentSize + 1;
          if (this.currentPage > tempPageNum) {
            this.input.pageNum = 0;
            this.currentPage = 1;
          }

          this.input.pageNum = (this.currentPage - 1) * this.currentSize;
          this.input.pageSize = this.currentSize;

          /**
           * 查询满足查询条件的角色列表
           */
          this.axios.post("http://localhost:9090/system/role/listByKeyword", this.input).then((response) => {
            this.tableData = response.data.list;
          })
        }else {
          this.tableData = []
        }
      })
    },


    /**
     * 查询全部状态账户
     */
    queryStatus(id) {
      switch (id) {
        case 1:
          this.roleStatus = '正常使用';
          this.input.status = 1;
          break;
        case 2:
          this.roleStatus = '禁用状态';
          this.input.status = 0;
          break;
        case 3:
          this.roleStatus = '全部状态';
          this.input.status = null;
          break;
      }
      this.listRoleByCondition();
    },


    /**
     * 业务：查询权限树数据源
     */
    menuPopups() {
      this.axios.get("http://localhost:9090/system/menu/getTreeVOAll").then((response) => {
        let newList = []; //定义一个新数组用来存放遍历的数据
        let jsonObjs = response.data.data.categories;
        for (let i = 0; i < jsonObjs.length; i++) {
          newList[i] = {
            key: jsonObjs[i].id,
            label: jsonObjs[i].name,
            children: jsonObjs[i].childrens
          };

          let jsonObjs2 = jsonObjs[i].childrens;
          if (jsonObjs2 != null) {
            for (let j = 0; j < jsonObjs2.length; j++) {
              newList[i].children[j] = {
                key: jsonObjs2[j].id,
                label: jsonObjs2[j].name,
                children: jsonObjs2[j].childrens
              };

              let jsonObjs3 = newList[i].children[j].children
              if (jsonObjs3 != null) {
                for (let k = 0; k < jsonObjs3.length; k++) {
                  newList[i].children[j].children[k] = {
                    key: jsonObjs3[k].id,
                    label: jsonObjs3[k].name,
                    children: jsonObjs3[k].children
                  };
                }
              }
            }
          }
        }
        this.treeData = newList;
      })
    },


    /**
     * 业务：回显角色信息
     */
    selectById(id) {
      this.axios.get("http://localhost:9090/system/role/getBackFillById?id=" + id).then((response) => {
        this.ruleForm = response.data;
        console.log("根据角色ID=【"+id+"】回显角色信息，获得昵称：【"+this.ruleForm.name+"】，(回显部分信息表示操作成功)");
      })
    },


    /**
     * 业务：回显当前角色拥有的权限列表
     */
    menuByRoleId(id) {
      this.ruleForm.id = id;
      this.axios.post("http://localhost:9090/system/role/roleMenuById", this.ruleForm).then((response) => {
          this.romeMenuEchoArray = response.data;
          console.log("角色权限回显结果："+this.romeMenuEchoArray)
          this.$refs.tree.setCheckedKeys(response.data)
      })
    },


    /**
     * 按钮：叉---权限列表弹窗
     */
    handleClose() {
      this.drawer = false;
    },


    /**
     * 按钮：取消按钮---权限列表弹窗
     */
    cancelForm() {
      this.drawer = false;
    },


    /**
     * 清空选中
     */
    clearC(){
      this.$refs.cascader.$refs.panel.clearCheckedNodes();
    },


    /**
     * 业务：获取分页，每页条数
     * @param val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentSize = val;
      this.listRoleByCondition();
    },


    /**
     * 业务：获取当前页数
     * @param val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.listRoleByCondition();
    },


    /**
     * 清除弹窗数据及遗留效果
     */
    closeDialog(ruleForm) {
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },
  },
  created() {
    this.listRoleByCondition();
  }
}

</script>
